<template>
  <div class="employee-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>员工管理</span>
          <el-button type="primary" @click="handleAdd">新增员工</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="姓名" class="form-item">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="性别" class="form-item">
          <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable style="width: 120px">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间" class="form-item">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
            style="width: 380px"
            :locale="zhCn"
          />
        </el-form-item>
        <el-form-item class="form-item operation-buttons">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">清空</el-button>
        </el-form-item>
      </el-form>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">+ 新增员工</el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">- 批量删除</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading" 
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="姓名" width="120" align="center" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column label="头像" width="100" align="center">
          <template #default="scope">
            <el-avatar :size="40" :src="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="所属部门" min-width="120" align="center" />
        <el-table-column prop="position" label="职位" min-width="120" align="center">
          <template #default="scope">
            {{ getPositionLabel(scope.row.position) }}
          </template>
        </el-table-column>
        <el-table-column prop="entrydate" label="入职日期" min-width="120" align="center" />
        <el-table-column prop="updateTime" label="最后操作时间" min-width="160" align="center" />
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          :locale="zhCn"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入员工用户名，2-20个字" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入员工姓名，2-10个字" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择" style="width: 100%">
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入员工手机号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-select v-model="form.position" placeholder="请选择" style="width: 100%">
                <el-option label="班主任" :value="1" />
                <el-option label="讲师" :value="2" />
                <el-option label="学工主管" :value="3" />
                <el-option label="教研主管" :value="4" />
                <el-option label="咨询师" :value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资" prop="salary">
              <el-input-number v-model="form.salary" :min="0" :precision="2" style="width: 100%" placeholder="请输入员工薪资" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="dept in deptList"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期" prop="entrydate">
              <el-date-picker
                v-model="form.entrydate"
                type="date"
                placeholder="请选择入职日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="头像" prop="avatar">
          <div class="avatar-upload-container">
            <el-upload
              class="avatar-uploader"
              action="#"
              name="file"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarUpload"
              accept=".jpg,.jpeg,.png"
            >
              <img v-if="form.avatar" :src="form.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">
              <p>图片大小不超过2M</p>
              <p>仅能上传PNG、JPEG、JPG等图片</p>
              <p>建议上传200*200或300*300尺寸的照片</p>
            </div>
          </div>
        </el-form-item>
        
        <!-- 工作经历 -->
        <el-form-item label="工作经历">
          <div>
            <el-button type="primary" @click="addExperience">新增工作经历</el-button>
            <div v-if="form.experiences.length > 0" class="work-experience-section">
              <div v-for="(exp, index) in form.experiences" :key="index" class="experience-item">
                <div class="experience-header">
                  <span>工作经历 {{ index + 1 }}</span>
                  <el-button type="danger" link @click="removeExperience(index)">删除</el-button>
                </div>
                <div class="experience-form">
                  <el-form-item label="时间" :prop="'experiences.' + index + '.startDate'" label-width="60px">
                    <el-date-picker
                      v-model="exp.dateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      @change="(dates) => handleDateRangeChange(dates, exp)"
                    />
                  </el-form-item>
                  <el-form-item label="公司" :prop="'experiences.' + index + '.company'" label-width="60px">
                    <el-input v-model="exp.company" placeholder="请输入公司名称" />
                  </el-form-item>
                  <el-form-item label="职位" :prop="'experiences.' + index + '.job'" label-width="60px">
                    <el-input v-model="exp.job" placeholder="请输入职位" />
                  </el-form-item>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { 
  getEmployeeList,
  deleteEmployee,
  addEmployee,
  getEmployeeById,
  updateEmployee,
  batchDeleteEmployees,
  uploadAvatar
} from '@/api/employee'
import { getDepartmentList } from '@/api/department'
import { Plus } from '@element-plus/icons-vue'

// 搜索表单数据
const searchForm = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  gender: undefined,
  startDate: '',
  endDate: ''
})

// 日期范围
const dateRange = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 部门列表
const deptList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const form = ref({
  id: '',
  username: '',
  name: '',
  gender: 1,
  phone: '',
  position: '',
  deptId: '',
  entrydate: '',
  salary: 0,
  avatar: '',
  experiences: []
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请选择职位', trigger: 'change' }
  ],
  deptId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  entrydate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ]
}

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 获取职位标签
const getPositionLabel = (position) => {
  const positions = {
    1: '班主任',
    2: '讲师',
    3: '学工主管',
    4: '教研主管',
    5: '咨询师'
  }
  return positions[position] || '未知'
}

// 获取员工列表
const fetchEmployeeList = async () => {
  try {
    loading.value = true
    const res = await getEmployeeList({
      page: searchForm.page,
      pageSize: searchForm.pageSize,
      name: searchForm.name,
      gender: searchForm.gender,
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    })
    
    if (res.code === 1) {
      tableData.value = res.data.rows || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error(error.message || '获取员工列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门列表
const fetchDepartmentList = async () => {
  try {
    const res = await getDepartmentList()
    if (res.code === 1) {
      deptList.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取部门列表失败')
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

// 搜索
const handleSearch = () => {
  searchForm.page = 1
  fetchEmployeeList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.gender = ''
  dateRange.value = []
  searchForm.page = 1
  searchForm.pageSize = 10
  fetchEmployeeList()
}

// 新增员工
const handleAdd = () => {
  dialogTitle.value = '新增员工'
  form.value = {
    id: '',
    username: '',
    name: '',
    gender: 1,
    phone: '',
    position: '',
    deptId: '',
    entrydate: '',
    salary: 0,
    avatar: '',
    experiences: []
  }
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = async (row) => {
  try {
    console.log('开始获取员工详情:', row.id)
    const res = await getEmployeeById(row.id)
    console.log('获取员工详情响应:', res)
    
    if (res && res.code !== 0) {
      dialogTitle.value = '编辑员工'
      // 处理工作经历的日期范围
      const employeeData = res.data || res
      if (employeeData.experiences) {
        employeeData.experiences = employeeData.experiences.map(exp => ({
          ...exp,
          dateRange: [exp.startDate, exp.endDate]
        }))
      }
      // 确保所有必要的字段都有值
      form.value = {
        id: '',
        username: '',
        name: '',
        gender: 1,
        phone: '',
        position: '',
        deptId: '',
        entrydate: '',
        salary: 0,
        avatar: '',
        experiences: [],
        ...employeeData  // 用服务器返回的数据覆盖默认值
      }
      dialogVisible.value = true
    } else {
      ElMessage.error(res?.msg || '获取员工信息失败')
    }
  } catch (error) {
    console.error('获取员工详情失败:', error)
    ElMessage.error('获取员工信息失败，请重试')
  }
}

// 删除员工
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该员工吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await deleteEmployee(row.id)
      if (res.code === 1) {
        ElMessage.success('删除成功')
        fetchEmployeeList()
      }
    } catch (error) {
      console.error('删除员工失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = { ...form.value }
        // 处理工作经历数据
        submitData.experiences = submitData.experiences.map(exp => ({
          startDate: exp.startDate,
          endDate: exp.endDate,
          company: exp.company,
          job: exp.job
        }))

        let res
        if (form.value.id) {
          // 编辑
          res = await updateEmployee(submitData)
        } else {
          // 新增
          res = await addEmployee(submitData)
        }
        
        if (res.code === 1) {
          ElMessage.success(form.value.id ? '修改成功' : '添加成功')
          dialogVisible.value = false
          fetchEmployeeList()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

// 处理日期范围变化
const handleDateRangeChange = (dates, experience) => {
  if (dates) {
    experience.startDate = dates[0]
    experience.endDate = dates[1]
  } else {
    experience.startDate = ''
    experience.endDate = ''
  }
}

// 添加工作经历
const addExperience = () => {
  form.value.experiences.push({
    company: '',
    job: '',
    startDate: '',
    endDate: '',
    dateRange: null
  })
}

// 移除工作经历
const removeExperience = (index) => {
  form.value.experiences.splice(index, 1)
}

// 分页相关
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  fetchEmployeeList()
}

const handleCurrentChange = (val) => {
  searchForm.page = val
  fetchEmployeeList()
}

// 选中的行
const selectedRows = ref([])

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  console.log('选中的行:', selection)
  selectedRows.value = selection
}

// 处理批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的员工')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 名员工吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id)
      const res = await batchDeleteEmployees(ids)
      if (res.code === 1) {
        ElMessage.success('批量删除成功')
        fetchEmployeeList()
      }
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error(error.message || '批量删除失败')
    }
  })
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = async (options) => {
  try {
    const res = await uploadAvatar(options.file)
    console.log('上传响应:', res)
    
    if (res.code === 1) {
      form.value.avatar = res.data
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error(res.msg || '头像上传失败')
    }
  } catch (error) {
    console.error('上传出错:', error)
    ElMessage.error('头像上传失败，请重试')
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchEmployeeList()
  fetchDepartmentList()
})
</script>

<style scoped>
.employee-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  width: 100%;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 0;
  flex: 1;
}

.search-form :deep(.operation-buttons) {
  display: flex;
  justify-content: flex-end;
  min-width: 200px;
}

.search-form :deep(.el-input),
.search-form :deep(.el-select) {
  width: 100%;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-upload-container {
  display: flex;
  align-items: flex-start;
  gap: 15px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.upload-tip p {
  margin: 0;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 89px;
  height: 89px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 89px;
  height: 89px;
  text-align: center;
  line-height: 89px;
}

.avatar {
  width: 89px;
  height: 89px;
  display: block;
  object-fit: cover;
}

.work-experience-section {
  margin-top: 10px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.experience-item {
  margin-bottom: 10px;
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
}

.experience-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.experience-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.experience-header span {
  font-size: 14px;
  color: #606266;
}

.experience-form {
  .el-form-item {
    margin-bottom: 10px;
  }

  .el-form-item__label {
    font-size: 13px;
  }

  .el-input__wrapper,
  .el-date-editor {
    font-size: 13px;
  }
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}

:deep(.el-input-number .el-input__wrapper) {
  width: 100%;
}
</style> 